package cn.zmit.kuxi.holder;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.activity.BaseActivity;
import cn.zmit.kuxi.activity.GoodsDetailActivity;
import cn.zmit.kuxi.activity.LoginActivity;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.contants.Url;
import cn.zmit.kuxi.entity.TodayHotEnity;
import cn.zmit.kuxi.event.EventFactory;
import cn.zmit.kuxi.image.ImageDisplayer;
import cn.zmit.kuxi.interfaces.OnAddToCartClickListener;
import cn.zmit.kuxi.interfaces.OnListItemSelectListener;
import cn.zmit.kuxi.request.RequestTask;

import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.ScreenUtils;
import com.xdroid.common.utils.ToastUtils;
import com.xdroid.functions.holder.ViewHolderBase;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;

/** * @author chenxu @parameter * @return */
public class TodayHotHolder extends ViewHolderBase<TodayHotEnity> {
	private Context context;
	private ImageView goodsImag, shoppingcarts;
	private TextView title, goodsName, joinName, allNeed, tv_progress_num;
	private ProgressBar progressBar;
	private RelativeLayout rlHot;
	private BaseActivity activity;
	private String userid;
	private String status;// 今日热门判断是否在购物车
	public static OnListItemSelectListener<TodayHotEnity> onlistItemSelect;

	private static OnAddToCartClickListener<TodayHotEnity> onAddToCartClickListener;

	Boolean haslog;

	@Override
	public View createView(LayoutInflater layoutInflater) {
		activity = (BaseActivity) layoutInflater.getContext();
		View view = layoutInflater.inflate(R.layout.item_main_gridview, null);
		goodsImag = (ImageView) view.findViewById(R.id.image_todayGoods_pic);
		shoppingcarts = (ImageView) view
				.findViewById(R.id.imag_hot_shoppingcarts);
		title = (TextView) view.findViewById(R.id.tv_today_goodsTitle);
		goodsName = (TextView) view.findViewById(R.id.tv_today);
		joinName = (TextView) view.findViewById(R.id.tv_join_num);
		// allNeed = (TextView) view.findViewById(R.id.tv_allNeed_num);
		tv_progress_num = (TextView) view.findViewById(R.id.tv_progress_num);
		progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
		rlHot = (RelativeLayout) view.findViewById(R.id.ll_hot);
		haslog = PreferenceHelper.readBoolean(activity,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.HAS_LOGGED,
				false);
		if (haslog) {
			userid = PreferenceHelper.readString(activity,
					SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");

		}
		return view;
	}
	@Override
	public void showData(final int position, final TodayHotEnity itemData) {
		if (itemData.getUrl() != null && itemData.getUrl().length() > 0) {
			ImageDisplayer.getInstance().dispalyImageWithRadius(
					Url.IMAGE_PICTURES + itemData.getUrl(), goodsImag, 0);

		} else {
			goodsImag.setImageResource(R.drawable.ic_launcher);
		}
		title.setText("第" + itemData.getTitle() + "期");
		goodsName.setText(itemData.getGoodsName());
		// joinName.setText("已参与：" + itemData.getJoinName());
		// allNeed.setText("总需人数：" + itemData.getNeedAll());
		if (itemData.getNeedAll() != null && itemData.getJoinName() != null) {
			double all = Integer.parseInt(itemData.getNeedAll());
			double join = Integer.parseInt(itemData.getJoinName());
			double result = ((join / all) * 100);
			progressBar.setMax(100);
			progressBar.setProgress((int) (result));
			tv_progress_num.setText("参与进度："+(int) (result) + "%");
		}
		status = itemData.getStatus();
		if (status != null && status.equals("1")) {
			shoppingcarts
					.setImageResource(R.drawable.button_hot_shopping_cart_red);
		} else {
			shoppingcarts
					.setImageResource(R.drawable.button_hot_shopping_cart_red);
		}
		rlHot.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				Bundle bundle = new Bundle();
				bundle.putString("gp_id", itemData.getGp_id());
				intent.putExtras(bundle);
				intent.setClass(activity, GoodsDetailActivity.class);
				activity.startActivity(intent);

			}
		});
		shoppingcarts.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// int all = Integer.parseInt(itemData.getNeedAll());
				// int count = Integer.parseInt(itemData.getJoinName());

				if (userid != null && userid.length() > 0) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("user_id", userid);
					map.put("gp_id", itemData.getGp_id());
					map.put("number", "1");
					RequestTask.getInstance().doAddCarts(activity, map,
							new onAddRequestListener());

					v.getLocationInWindow(start_location);// 这是获取购买按钮的在屏幕的X、Y坐标（这也是动画开始的坐标）

				} else {
					ToastUtils.show(activity, "您未登陆");
					Intent intent = new Intent();
					intent.setClass(activity, LoginActivity.class);
					activity.startActivity(intent);
				}
			}
		});
	}

	int enough;
	int[] start_location = new int[2];// 一个整型数组，用来存储按钮的在屏幕的X、Y坐标

	private class onAddRequestListener extends OnRequestListenerAdapter<Object> {
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			super.onDone(request, response, dataType);
			JsonData jsonData = JsonData.create(response);
			String data = jsonData.optString("code");
			if (data.equals("1")) {
				int count = jsonData.optInt("my_goods_count");
				EventFactory.sendUpdateCartCount(count);
				ToastUtils.show(activity, "加入成功");
				shoppingcarts
						.setImageResource(R.drawable.button_hot_shopping_cart_red);
				ImageView buyImg = new ImageView(activity);// buyImg是动画的图片，我的是一个小球（R.drawable.sign）
				buyImg.setImageDrawable(shoppingcarts.getDrawable());
				// buyImg.setImageBitmap(ImageUtils.getRoundedCornerBitmap(CommonUtils
				// .drawableToBitmap(shoppingcarts.getDrawable(),
				// (int) ScreenUtils.dpToPx(context, 160),
				// (int) ScreenUtils.dpToPx(context, 120)), 360));

				setAnim(buyImg, start_location);// 开始执行动画
			}
			if (data.equals("0")) {
				// 新购物车动画
				Log.e("e", enough + "");
				ToastUtils.show(activity, "数量不足");
			}
		}
	}

	public static void setOnAddToCartClickListener(
			OnAddToCartClickListener<TodayHotEnity> onAddToCartClickListener) {
		TodayHotHolder.onAddToCartClickListener = onAddToCartClickListener;
	}

	private ViewGroup anim_mask_layout;// 动画层

	/**
	 * @Description: 创建动画层
	 * @param
	 * @return void
	 * @throws
	 */
	private ViewGroup createAnimLayout() {
		ViewGroup rootView = (ViewGroup) activity.getWindow().getDecorView();
		LinearLayout animLayout = new LinearLayout(activity);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);
		animLayout.setLayoutParams(lp);
		animLayout.setId(Integer.MAX_VALUE);
		animLayout.setBackgroundResource(android.R.color.transparent);
		rootView.addView(animLayout);
		return animLayout;
	}

	private View addViewToAnimLayout(final ViewGroup vg, final View view,
			int[] location) {
		int x = location[0];
		int y = location[1];
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		lp.leftMargin = x;
		lp.topMargin = y;
		view.setLayoutParams(lp);
		return view;
	}

	private void setAnim(final View v, int[] start_location) {
		anim_mask_layout = null;
		anim_mask_layout = createAnimLayout();
		anim_mask_layout.addView(v);// 把动画小球添加到动画层
		final View view = addViewToAnimLayout(anim_mask_layout, v,
				start_location);
		int[] end_location = new int[2];// 这是用来存储动画结束位置的X、Y坐标
		// shopCart.getLocationInWindow(end_location);// shopCart是那个购物车
		end_location[0] = (int) ((ScreenUtils.getScreenWidth(activity) / 5) * 4 - ScreenUtils
				.dpToPx(activity, 48));
		end_location[1] = (int) (ScreenUtils.getScreenHeight(activity) - ScreenUtils
				.dpToPx(activity, 45));
		// 计算位移
		int endX = end_location[0] - start_location[0];// 动画位移的X坐标
		int endY = end_location[1] - start_location[1];// 动画位移的y坐标
		TranslateAnimation translateAnimationX = new TranslateAnimation(0,
				endX, 0, 0);
		translateAnimationX.setInterpolator(new LinearInterpolator());
		translateAnimationX.setRepeatCount(0);// 动画重复执行的次数
		translateAnimationX.setFillAfter(true);

		TranslateAnimation translateAnimationY = new TranslateAnimation(0, 0,
				0, endY);
		translateAnimationY.setInterpolator(new AccelerateInterpolator());
		translateAnimationY.setRepeatCount(0);// 动画重复执行的次数
		translateAnimationX.setFillAfter(true);

		AnimationSet set = new AnimationSet(false);
		set.setFillAfter(false);
		set.addAnimation(translateAnimationY);
		set.addAnimation(translateAnimationX);
		set.setDuration(800);// 动画的执行时间
		view.startAnimation(set);
		// 动画监听事件
		set.setAnimationListener(new AnimationListener() {
			// 动画的开始
			@Override
			public void onAnimationStart(Animation animation) {
				v.setVisibility(View.VISIBLE);
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
			}

			// 动画的结束
			@Override
			public void onAnimationEnd(Animation animation) {
				v.setVisibility(View.GONE);
				// buyNum++;//让购买数量加1
				// buyNumView.setText(buyNum + "");//
				// buyNumView.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
				// buyNumView.show();
			}
		});

	}
}
